import React, { useState, useEffect } from 'react';
import { Upload, Modal } from "antd";
import $http from "@/services"
export default function UploadComp({ avatar = null, getNewAvatar }) {
    const [token, setToken] = useState("");
    const [fileList, setFileList] = useState([]);
    const [previewImg, setPreviewImg] = useState("");
    const [previewOpen, setPreviewOpen] = useState(false)
    useEffect(() => {
        if (avatar) {
            setFileList([{ url: avatar }]);
            setPreviewImg(avatar);
        }
        _getToken();
    }, [])
    const _getToken = async () => {
        const { data } = await $http.getUploadToken({
            bucket: "reactimages",
            uploadUrl: "rqb5a7nj2.hn-bkt.clouddn.com",
            accessKey: "K6Jy9rt-IaNINsCoyDLrM2PrHZiyntdql1B9N1Vt",
            secretKey: "GOq_Ea0XnUWYg2kj__qvQn8-B75FM1owKbSrGTsw"
        });
        setToken(data);
    }
    const handlePreview = (info) => {
        setPreviewOpen(true)
    }

    // 修改内容处理
    const handleChange = (info) => {
        setFileList(info.fileList);
        // 状态请求结束
        if (info.file.status === "done") {
            const newAvatar = "http://rqeptin29.hd-bkt.clouddn.com/" + info.file.response.url.split("/")[1];
            setPreviewImg(newAvatar);
            getNewAvatar(newAvatar);
        }
    }

    // 取消
    const handleCancel = () => setPreviewOpen(false);
    return (
        <>
            <Upload
                maxCount={1}
                action="https://up-z0.qiniup.com/"
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
                data={{ token }}
            >选择图片</Upload>
            <Modal
                closable={false}
                open={previewOpen}
                footer={null}
                onCancel={handleCancel}>

                <img
                    alt="example"
                    style={{
                        width: '100%',
                    }}
                    src={previewImg}
                />
            </Modal>
        </>
    )
}
